<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>线性一致性（二）——细究linearizability - 读论文</title>


        <!-- Custom HTML head -->
        
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="favicon.svg">
        <link rel="shortcut icon" href="favicon.png">
        <link rel="stylesheet" href="css/variables.css">
        <link rel="stylesheet" href="css/general.css">
        <link rel="stylesheet" href="css/chrome.css">
        <link rel="stylesheet" href="css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->

        <!-- MathJax -->
        <script async type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded affix "><a href="chapter_1.html">读论文活动</a></li><li class="chapter-item expanded affix "><li class="part-title">6.824 分布式系统</li><li class="chapter-item expanded "><a href="Mapreduce.html"><strong aria-hidden="true">1.</strong> Mapreduce</a></li><li class="chapter-item expanded "><a href="GFS.html"><strong aria-hidden="true">2.</strong> GFS</a></li><li class="chapter-item expanded "><a href="VM-FT.html"><strong aria-hidden="true">3.</strong> VM-FT</a></li><li class="chapter-item expanded "><a href="Raft.html"><strong aria-hidden="true">4.</strong> Raft</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="Raft0.html"><strong aria-hidden="true">4.1.</strong> 感性认识Raft</a></li><li class="chapter-item expanded "><a href="Raft1.html"><strong aria-hidden="true">4.2.</strong> 什么是Raft？</a></li><li class="chapter-item expanded "><a href="Raft2.html"><strong aria-hidden="true">4.3.</strong> 复制状态机（Replicated State Machine）</a></li><li class="chapter-item expanded "><a href="Raft3.html"><strong aria-hidden="true">4.4.</strong> What's wrong with Paxos?</a></li><li class="chapter-item expanded "><a href="Raft4.html"><strong aria-hidden="true">4.5.</strong> 向可理解性进军</a></li><li class="chapter-item expanded "><a href="Raft5.html"><strong aria-hidden="true">4.6.</strong> Raft共识算法（零）</a></li><li class="chapter-item expanded "><a href="Raft6.html"><strong aria-hidden="true">4.7.</strong> Raft共识算法（一）——基础概念</a></li><li class="chapter-item expanded "><a href="Raft7.html"><strong aria-hidden="true">4.8.</strong> Raft共识算法（二）——选举leader</a></li><li class="chapter-item expanded "><a href="Raft8.html"><strong aria-hidden="true">4.9.</strong> Raft共识算法（三）——日志备份（log replication）</a></li><li class="chapter-item expanded "><a href="Raft9.html"><strong aria-hidden="true">4.10.</strong> Raft共识算法（四）——安全性和选举限制</a></li><li class="chapter-item expanded "><a href="Raft10.html"><strong aria-hidden="true">4.11.</strong> Raft共识算法（五）——如何提交之前term里的entry</a></li><li class="chapter-item expanded "><a href="Raft11.html"><strong aria-hidden="true">4.12.</strong> Raft共识算法（六）——安全性定理</a></li><li class="chapter-item expanded "><a href="Raft12.html"><strong aria-hidden="true">4.13.</strong> Raft共识算法（七）——如果follower/candidate宕机了</a></li><li class="chapter-item expanded "><a href="Raft13.html"><strong aria-hidden="true">4.14.</strong> Raft共识算法（八）——时间与可用性</a></li><li class="chapter-item expanded "><a href="Raft14.html"><strong aria-hidden="true">4.15.</strong> 成员变更</a></li><li class="chapter-item expanded "><a href="Raft15.html"><strong aria-hidden="true">4.16.</strong> 日志压缩</a></li><li class="chapter-item expanded "><a href="Raft16.html"><strong aria-hidden="true">4.17.</strong> 与Client的交互</a></li><li class="chapter-item expanded "><a href="Raft17.html"><strong aria-hidden="true">4.18.</strong> 实验时遇到的bug</a></li><li class="chapter-item expanded "><a href="Raft18.html"><strong aria-hidden="true">4.19.</strong> 总结</a></li></ol></li><li class="chapter-item expanded "><a href="Zookeeper.html"><strong aria-hidden="true">5.</strong> Zookeeper</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="linearizability1.html"><strong aria-hidden="true">5.1.</strong> 线性一致性（一）——基础概念</a></li><li class="chapter-item expanded "><a href="linearizability2.html" class="active"><strong aria-hidden="true">5.2.</strong> 线性一致性（二）——细究linearizability</a></li><li class="chapter-item expanded "><a href="zk_intro.html"><strong aria-hidden="true">5.3.</strong> 引言</a></li><li class="chapter-item expanded "><a href="zk_service.html"><strong aria-hidden="true">5.4.</strong> Zookeeper Service</a></li><li class="chapter-item expanded "><a href="zk_api.html"><strong aria-hidden="true">5.5.</strong> Zookeeper API</a></li><li class="chapter-item expanded "><a href="zk_prop.html"><strong aria-hidden="true">5.6.</strong> Zookeeper的性质</a></li><li class="chapter-item expanded "><a href="zk_ex.html"><strong aria-hidden="true">5.7.</strong> 基于Zookeeper实现锁</a></li></ol></li><li class="chapter-item expanded "><a href="CRAQ.html"><strong aria-hidden="true">6.</strong> CRAQ</a></li><li class="chapter-item expanded "><a href="lamport_clock.html"><strong aria-hidden="true">7.</strong> Time, Clocks, and the Ordering of Events in a Distributed System</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="lamport_clock1.html"><strong aria-hidden="true">7.1.</strong> 引言</a></li><li class="chapter-item expanded "><a href="lamport_clock_partial_order.html"><strong aria-hidden="true">7.2.</strong> 偏序关系</a></li><li class="chapter-item expanded "><a href="lamport_logic_clock.html"><strong aria-hidden="true">7.3.</strong> 逻辑时钟</a></li><li class="chapter-item expanded "><a href="lamport_total_order.html"><strong aria-hidden="true">7.4.</strong> 全序关系</a></li><li class="chapter-item expanded "><a href="lamport_clock_ana_behave.html"><strong aria-hidden="true">7.5.</strong> 异常事件</a></li><li class="chapter-item expanded "><a href="lamport_p_clock.html"><strong aria-hidden="true">7.6.</strong> 物理时钟</a></li><li class="chapter-item expanded "><a href="lamport_end.html"><strong aria-hidden="true">7.7.</strong> 结论</a></li></ol></li><li class="chapter-item expanded "><li class="part-title">6.828 操作系统</li><li class="chapter-item expanded "><a href="828intro.html"><strong aria-hidden="true">8.</strong> Killer of Microseconds</a></li><li class="chapter-item expanded "><a href="cloudlab.html"><strong aria-hidden="true">9.</strong> CloudLab</a></li><li class="chapter-item expanded "><a href="dpdk.html"><strong aria-hidden="true">10.</strong> DPDK</a></li><li class="chapter-item expanded "><a href="spdk.html"><strong aria-hidden="true">11.</strong> SPDK</a></li><li class="chapter-item expanded "><a href="Shenango.html"><strong aria-hidden="true">12.</strong> Shenango</a></li><li class="chapter-item expanded "><a href="TritonSort.html"><strong aria-hidden="true">13.</strong> TritonSort</a></li><li class="chapter-item expanded "><a href="Profiling.html"><strong aria-hidden="true">14.</strong> Profiling a warehouse-scale computer</a></li><li class="chapter-item expanded affix "><li class="part-title">6.828 - Network</li><li class="chapter-item expanded affix "><li class="part-title">CS244 - Advanced Topics in Networking</li><li class="chapter-item expanded "><a href="DARPA_NET.html"><strong aria-hidden="true">15.</strong> The Design Philosophy of The DARPA Internet Protocols</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="DARPA_NET2.html"><strong aria-hidden="true">15.1.</strong> Second Level Goals</a></li><li class="chapter-item expanded "><a href="DARPA_NET3.html"><strong aria-hidden="true">15.2.</strong> Types of Service</a></li><li class="chapter-item expanded "><a href="DARPA_NET4.html"><strong aria-hidden="true">15.3.</strong> Varieties of Networks</a></li><li class="chapter-item expanded "><a href="DARPA_NET5.html"><strong aria-hidden="true">15.4.</strong> Architecture and Implementation</a></li><li class="chapter-item expanded "><a href="DARPA_NET6.html"><strong aria-hidden="true">15.5.</strong> Datagrams</a></li></ol></li><li class="chapter-item expanded "><li class="part-title">最后</li><li class="chapter-item expanded "><a href="end.html"><strong aria-hidden="true">16.</strong> 最后</a></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">读论文</h1>

                    <div class="right-buttons">
                        <a href="print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="细究linearizability"><a class="header" href="#细究linearizability">细究linearizability</a></h1>
<h2 id="linearizability与happens-before"><a class="header" href="#linearizability与happens-before">linearizability与happens-before</a></h2>
<p>注意&quot;操作A的结束时间发生在操作B的开始时间之前&quot;，与&quot;A发生在B之前&quot;的这种&quot;happens-before&quot;概念不同。<br />
happen-before关系是一个定义消息发送和接收的术语（编译器/多线程里好像经常用这个词？）；</p>
<p><img src="./assets/linear_happens_before.png" alt="linear_happens_before.png" /></p>
<p>在happens-before的定义下，如果b在a之后先执行，要么a和b在相同的任务执行流（进程/线程）里；要么a和b在不同的process1和process2里，且process1和process2通过发送message通信的方式确定a和b的执行顺序。</p>
<p>假设有两个操作，分别在不同的process里，且这两个process并没有相互通信，那么在并发的情况下，这两个操作a和b则有三种可能：</p>
<ol>
<li>a-&gt;b，a先执行，b后执行；</li>
<li>b-&gt;a，b先执行，a后执行；</li>
<li>a, b重叠（因为a和b操作都是耗时的）。</li>
</ol>
<h2 id="real-time"><a class="header" href="#real-time">real-time</a></h2>
<p>线性一致性定义了real time。<br />
在这个概念里，我们有一个想象中的、带有上帝视角的全局观察者，它可以立即观察到任何节点在任何时候的状态，也可以观察到任何节点的操作在什么时候开始，或者在什么时候结束。<br />
或者说系统中每个节点都有一个完美的用来同步的时钟，有了这个时钟之后，我们就可以精确地考察系统里每个节点的状态了。</p>
<p>不过现实世界中，不存在这样一个全局观察者或者理想的同步时钟，但是我们在分析系统的时候，我们可以假设它们存在。</p>
<h2 id="get操作之间的关系"><a class="header" href="#get操作之间的关系">get操作之间的关系</a></h2>
<p>线性一致性不仅关心set操作和get操作之间的关系，同时它还关心get操作和get操作之间的关系。</p>
<p align="center"><img width="60%" src="./assets/zk_linear3.png" alt="zk_linear3" /></p>
<p>如上图所示，我们以一个quorum系统来举例子。虽然这个系统采用了quorum制度，但是它并不能保证线性一致性。</p>
<ol>
<li>一开始client1将<code>x</code>设置为<code>v1</code>，假设A很快更新了它的备份状态机里<code>x</code>的值，然而B、C的响应地很慢。</li>
<li>client2从A、B里读数据，发现A、B的返回结果不一致，并决定根据值的时间戳采纳A的结果<code>v1</code>。</li>
<li>client2的读操作结束之后，client2从B、C里去读数据，收到了<code>v0</code>的过期数据，由于它不知道A里面有最新的数据<code>v1</code>，于是决定采纳<code>v0</code>作为<code>x</code>的值。</li>
</ol>
<p>如此一来，client3观察到的数据就比client2观察到的数据要老。<br />
从real-time的角度来看，client3的读操作发生在client2的读操作之后。对于线性一致性的系统来说，这种行为是不允许的。</p>
<h2 id="abd算法"><a class="header" href="#abd算法"><a href="https://cs.neea.dev/distributed/abd/">ABD算法</a></a></h2>
<p>庆幸的是，使用quorum制度进行读写，也是有可能使get/set具有线性一致性的。</p>
<p>首先，为了简单起见，我们先假设只有一个指定的节点可以进行set操作，之后我们再抛弃这个假设。</p>
<p>考察下图，在这个模型中，client1给A、B、C发送set请求，并等待过半节点的返回（只有过半的节点都修改成功后，这个set操作才算是修改成功）。<br />
与上图一样，A收到了请求，B、C没有收到，A修改了自身状态的<code>x</code>值为<code>v1</code>。</p>
<p align="center"><img width="60%" src="./assets/zk_linear_abd.png" alt="zk_linear_abd" /></p>
<p>对于get操作来说，我们增加一些规则：</p>
<ol>
<li>client第一步必须先给所有的节点发送请求，并等待大多数节点的回复。</li>
<li>如果某些节点返回的数据比其他节点的要新（这个新是通过对比时间戳进行比较的），client会把最新的数据广播出去，如果收到大多数节点成功返回的response，这个操作就算作成功。<br />
我们管这种广播操作叫做read repair。在广播的过程中，如果一个节点通过对比之后发现自己状态机里的数据是过期的，则会更新自己的数据之后再返回成功。</li>
<li>只有当client确定最新的数据被存储大多数（或者说是法定节点数）的节点里面之后，get操作才会结束。</li>
</ol>
<p>这样的话，大多数节点要么返回经过read repair修复成功的response，要么一开始就返回最新的数据。</p>
<p>比如说上图，client2给A、B、C发送get请求，分别收到来自A、B的<code>(t1, v1)</code>、<code>(t0, v0)</code>，于是它认为最新的数据是<code>(t1, v1)</code>，它就会广播set(t1, v1)这个操作给系统中的节点，
于是B、C收到这个请求之后，就会更新自己的状态。当client2收到B、C成功返回的response之后，它就结束get操作，并认为此时<code>x</code>的值是<code>v1</code>。</p>
<blockquote>
<p>这里有一个diff，当client进行get操作，在第一阶段收到大多数server的response的之后。<br />
剑桥的课件里的说法是给掉队的server发送set操作，而有的资料是说将set操作广播给系统里的所有节点。<br />
欢迎你来指出这两个说法哪一个是正确的。</p>
</blockquote>
<p>这个方法叫ABD算法（1995年提出），作者是Attiya, Bar-Noy, and Dolev。</p>
<p>它保证了系统可以进行线性一致地读和写。<br />
因为每当get或者set请求结束的时候，我们都能够确定读/写的数据已经被写入到了大多数节点里的状态机里。</p>
<h2 id="将abd算法进行推广"><a class="header" href="#将abd算法进行推广">将ABD算法进行推广</a></h2>
<p>刚才我们假设只有一个节点可以执行set操作，现在我们来尝试将ABD算法推广到多个节点都能够执行set操作的情形。</p>
<p>我们需要有一个能够反映出real-time的时间戳，来确保不同操作之间的顺序。<br />
令第一个操作<code>set(x, v1)</code>携带的时间戳是<code>t1</code>；第二个操作<code>set(x, v2)</code>携带的时间戳是<code>t2</code>。<br />
如果第一个操作结束之后，第二个操作才开始，那么我们可以肯定，<code>t1&lt;t2</code>。</p>
<blockquote>
<p>然而，不同的client可能会并发地执行set操作，如此一来可能会出现不同的操作具有相同的时间戳的情况。<br />
为了区分这种情况，我们可以给每个client一个唯一Id，并且结合clientId去比较时间戳。</p>
<p>当client进行get操作时，假设来自不同server的response里，时间戳相同但是值不同：<br />
可以安排一个clientId的优先级对比规则，通过对比优先级，client来确定应该采纳哪一个response（Lamport的时间戳也是如此定义的）。</p>
</blockquote>
<p>这个算法确保了在任意节点都可以执行set/get操作的情况下，系统仍能保证线性一致性。</p>
<h2 id="遗留问题"><a class="header" href="#遗留问题">遗留问题</a></h2>
<p>剑桥的课件里还提到了线性一致的CAS操作，里面还提到了偏序和全序。</p>
<ol>
<li>如何保证线性一致的CAS操作？</li>
<li>什么是<a href="https://eli.thegreenplace.net/2018/partial-and-total-orders/">偏序和全序</a>？在分布式系统里有什么应用？</li>
<li><a href="https://mit-public-courses-cn-translatio.gitbook.io/mit6-824/lecture-07-raft2/7.6-qiang-yi-zhi-linearizability">824的lecture</a>里，莫里斯教授列举了很多种情形，观察里面的例子，你是否能得出和莫里斯一样的结论？</li>
</ol>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="linearizability1.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>

                            <a rel="next" href="zk_intro.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="linearizability1.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>

                    <a rel="next" href="zk_intro.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>




        <script type="text/javascript">
            window.playground_copyable = true;
        </script>


        <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="searcher.js" type="text/javascript" charset="utf-8"></script>

        <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->


    </body>
</html>
